<?php
namespace app\admin\controller;

use app\common\model\Brands;
use think\Exception;
use think\Request;
use app\common\model\Brands as BrandsModel;
use app\common\model\Styles as StylesModel;
use think\Db;

/**
 * 跟平台有关的api的调用
 * Class Busapi
 * @package app\admin\controller
 */
class DataApi extends Base {

    //protected $api_hosts = 'http://318.ogmall.com';
    protected $api_hosts = 'http://xcx.ogmall.com:8080';

    protected $request_param = [
        'token'=>'',
    ];

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $key = 'ogmall-small-program';
        $this->request_param['token'] = $this->getEncrypt($key);
    }


    /**
     * 更新风格
     */
    public function updateStyles(){
        $api = $this->createApi("/api/styles",[]);
        $styles = $this->curl($api);
        $styles = json_decode($styles,true);
        if(isset($styles['status']) && $styles['status'] ){
            $data = $styles['data'];
            $now = time();
            foreach($data as $key => $val ){
                $style = StylesModel::where('oid',$val['id'])->find();
                if($style){
                    $style['name'] = $val['name'];//如果存在 同步名称
                    $style['introduce'] = empty($val['introduce'])?'':$val['introduce'];
                    $style['update_time'] = $now;
                    $style->save();
                }else{
                    $style = [];
                    $style['oid'] = $val['id'];
                    $style['name'] = $val['name'];
                    $style['introduce'] = empty($val['introduce'])?'':$val['introduce'];
                    $style['update_time'] = $now;
                    StylesModel::create($style);
                }
            }
            $this->success("更新成功");
        }
        $this->error("暂时没有数据更新");
    }


    /**
     * 根据风格更新品牌
     */
    public function updateBrand(Request $request){
        $style = StylesModel::where(['is_brand_update'=>0])->find();
        if(!$style){
            $this->error("更新完毕");
        }

        try{
            $page_no = 1;
            $totalPage = 0;
            do{
                $api = $this->createApi('/api/brand/ofStyle',['styleId'=>$style->oid,'pageNo'=>$page_no,'pageSize'=>'20']);
                $res = $this->curl($api);
                $res = json_decode($res,true);

                if(isset($res['status']) && $res['status'] && !empty($res['data'])){
                    $totalPage = $res['data']['pageResult']['totalPage'];
                    //更新
                    $list = $res['data']['list'];

                    $now = time();
                    foreach($list as $key => $val ){
                        $brand = BrandsModel::where(['oid'=>$val['id']])->find();
                        if($brand){
                            $brand['image'] = $val['image'];
                            $brand['head_image'] = $val['headImage'];
                            $brand["name"]      = $val['name'];
                            $brand['update_time'] = $now;
                            $brand->save();
                        }else{
                            $brand = [];
                            $brand['image'] = $val['image'];
                            $brand['head_image'] = $val['headImage'];
                            $brand["name"]      = $val['name'];
                            $brand['update_time'] = $now;
                            $brand['soid'] = $style->oid;
                            $brand['oid']  = $val['id'];
                            BrandsModel::create($brand);
                        }
                    }
                }

                $page_no++;
            } while ( $page_no <= $totalPage );
        }catch(\Exception $e){
            $this->error($e->getMessage());
        }


        $style->is_brand_update = 1;
        $style->save();

        $this->success($style['name']."更新成功");
    }


    /**
     * 根据品牌更新产品  这个不需要了 产品直接从接口获取了
     * @param Request $request
     */
    public function updateProduct(Request $request){
        $brand = StylesModel::where(['is_product_update'=>0])->find();
        if(!$brand){
            $this->error("更新完毕");
        }

        try{
            $page_no = 1;
            $totalPage = 0;
            do{
                $api = $this->createApi('/api/brand/products',['styleId'=>$brand->oid,'pageNo'=>$page_no,'pageSize'=>'20']);
                $res = $this->curl($api);
                $res = json_decode($res,true);

                if(isset($res['status']) && $res['status'] && !empty($res['data'])){
                    $totalPage = $res['data']['pageResult']['totalPage'];
                    //更新
                    $list = $res['data']['list'];

                    $now = time();
                    foreach($list as $key => $val ){
                        $brand = BrandsModel::where(['oid'=>$val['id']])->find();
                        if($brand){
                            $brand['image'] = $val['image'];
                            $brand['head_image'] = $val['headImage'];
                            $brand["name"]      = $val['name'];
                            $brand['update_time'] = $now;
                            $brand->save();
                        }else{
                            $brand = [];
                            $brand['image'] = $val['image'];
                            $brand['head_image'] = $val['headImage'];
                            $brand["name"]      = $val['name'];
                            $brand['update_time'] = $now;
                            $brand['soid'] = $style->oid;
                            $brand['oid']  = $val['id'];
                            BrandsModel::create($brand);
                        }
                    }
                }

                $page_no++;
            } while ( $page_no <= $totalPage );
        }catch(\Exception $e){
            $this->error($e->getMessage());
        }


        $brand->is_brand_update = 1;
        $brand->save();

        $this->success($brand['name']."更新成功");
    }

    /**
     * 跟新某个表的update 字段
     * @param Request $request
     */
    public function resetUpdateState(Request $request){
        $table = $request->param('t');
        $column = $request->param('c');
        //可以允许的表 和 字段
        $table_list = ['styles'];
        $column_list = ['is_brand_update'];

        if(!in_array($table,$table_list)){
            $this->error("不合法的请求");
        }

        if(!in_array($column,$column_list)){
            $this->error("不合法的请求");
        }

        try{
            $res = Db::table($table)->where([$column=>1])->update([$column=>0]);
        }catch( \Exception $e ){
            $this->error($e->getMessage());
        }


        $this->success("更新成功");

    }



    public function updateProvince(){
        $this->success("更新成功");
        $api = $this->api_hosts.'/api/getProvinces';
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $provinces = $this->curl($api);

        $provinces = json_decode($provinces,true);
        if( !$provinces || !$provinces['status'] ){
            throw new \Exception("省份数据错误");
        }
        $now = time();
        $res = Db::query('truncate table address');
        foreach( $provinces['data'] as $key => &$val ){
            $val['apid'] = 0;
            $val['type'] = 0;
            $val['update_time'] = $now;
            $val['aid'] = $val['id'];// aid 是平台id
            unset($val['id']);
        }
        unset($val);
        $res = Db::table('address')->insertAll($provinces['data']);

        $this->success("更新省份成功",'',$provinces['data']);

    }


    /**
     * @param Request $request
     */
    public function updateCity(Request $request){
        $province_id = $request->param('province_id');

        $api    = $this->api_hosts.'/api/getCities';
        $this->request_param['provinceId'] = $this->getEncrypt($province_id);
        $query  = http_build_query($this->request_param);
        $api   .= "?".$query;
        $cities = $this->curl($api);
        $cities = json_decode($cities,true);
        $now = time();
        if($cities['status']){
            foreach( $cities['data'] as $key => &$val ){
                $val['apid'] = $province_id;
                $val['type'] = 1;
                $val['update_time'] = $now;
                $val['aid'] = $val['id'];
                unset($val['id']);
            }
            unset($val);
            $res = Db::table('address')->insertAll($cities['data']);
            $this->success("更新成功",'',$cities['data']);
        }
        $this->success("更新成功",'',[]);
    }


    /**
     * 系统禁止了 多进程函数 可以利用curl来模拟 这样不就ok了
     * @param Request $request
     */
    public function updateDistrict(Request $request){
        $city_id = $request->param('city_id');
        $api = $this->api_hosts.'/api/getDistricts';
        $this->request_param['cityId'] = $this->getEncrypt($city_id);
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $districts = $this->curl($api);
        $districts = json_decode($districts,true);
        $now = time();
        if($districts['status']){
            foreach( $districts['data'] as $key => &$val ){
                $val['apid'] = $city_id;
                $val['type'] = 2;
                $val['update_time'] = $now;
                $val['aid'] = $val['id'];
                unset($val['id']);
            }
            unset($val);
            $res = Db::table('address')->insertAll($districts['data']);
            $this->success("更新成功",'',$districts['data']);
        }
        $this->success("更新成功",'',[]);
    }




    /**
     * 获取所有地区
     */
    public function getAllDistrict(){
        $data = AddressModel::where('type',2)->select();
        $data = collection($data)->toArray();
        $this->success("获取成功",'',$data);
    }


    /**
     * 更新B端和城市运营商的数据  还要增加一个判断是否单进程 不能并发操作
     * @throws
     */
    public function updateCompany(){
        $address = AddressModel::where(['type'=>2,'get_company'=>'0'])->order('id desc')->find();
        //$address = AddressModel::where(['type'=>2,'aid'=>'1801','get_company'=>0])->order('id desc')->find();
        if(!$address){
            $this->error("更新完毕");
        }

        $api = $this->api_hosts.'/api/getCompanys';
        $district_id = $address->aid; //老平台的地址id
        $this->request_param['districtId'] = $this->getEncrypt($district_id);
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $companies = $this->curl($api);
        $companies = json_decode($companies,true);

        if($companies['status']){
            //有公司数据  先构造地址
            $district_id = $address['aid'];
            $city_id = 0;
            $province_id = 0;
            $belong_to = 0;

            $city = AddressModel::where(['type'=>1])->where('aid',$address['apid'])->find();
            if($city){
                $city_id = $city['aid'];
                $province = AddressModel::where(['type'=>0])->where('aid',$city['apid'])->find();
                if($province){
                    $province_id = $province['aid'];
                }
            }
            $companies = $companies['data'];
            $data = [];
            $now = time();
            if(!empty($companies['agentData'])){
                //$belong_to = $companies['agentData']["agentUId"]; //给装修公司赋值用 但是公司的id 在本地要用本地数据
                $data['company_name'] = $companies['agentData']['agentName'];
                $data['company_id']   = $companies['agentData']["agentUId"];
                $data['update_time']  = $now;
                $data['province_id']  = $province_id;
                $data['city_id']      = $city_id;
                $data['district_id']  = $district_id;//对与城市运营商 这个值有没有都无所谓了 因为一个城市管几个区 这里以后看看怎么弄
                $data['type']         = 1;
                $company = Db::table('company')->where('company_id',$data['company_id'])->where('type','1')->find(); //加上type 过滤是为了防止 平台方 id跟地址id一样重复 就糟糕   address的id 市和区会有重复的id 好烦
                if($company){
                    Db::table('company')->where('company_id',$data['company_id'])->where('type','1')->update($data);
                    $belong_to = $company['id'];  //belong_to 用本地id
                }else{
                    $id = Db::table('company')->insertGetId($data);
                    $belong_to = $id;
                }
            }
            $data = [];
            if(!empty($companies['companyData'])){
                foreach($companies['companyData'] as $key => $val){
                    $data['company_name'] = $val['companyName'];
                    $data['company_id']   = $val['companyUId'];
                    $data['update_time']  = $now;
                    $data['province_id']  = $province_id;
                    $data['city_id']      = $city_id;
                    $data['district_id']  = $val['districtId'];
                    $data['belong_to']    = $belong_to;
                    $data['type']         = 0;
                    $company = Db::table('company')->where('company_id',$data['company_id'])->where('type','0')->count(); //加上type 过滤是为了防止 平台方 id跟地址id一样重复 就糟糕
                    if($company){
                        Db::table('company')->where('company_id',$data['company_id'])->where('type','0')->update($data);
                    }else{
                        Db::table('company')->insert($data);
                    }
                }
            }


        }
        AddressModel::update(['get_company'=>'1'],['id'=>$address['id']]);
        $this->success($address['name']." 更新成功...");
        //如果有数据 这里应该是先保存 再打散然后随机的排列数据 保证公平

    }


    /**
     * 产生api地址
     * @param $path
     * @param $data
     * @return string
     */
    protected function createApi($path,$data){
        $api    = $this->api_hosts.$path;
        foreach($data as $key=> $val ){
            $this->request_param[$key] = $this->getEncrypt($val);
        }
        $query  = http_build_query($this->request_param);
        $api   .= "?".$query;

        return $api;
    }

    /**
     * post 请求
     * @param $url
     * @return mixed
     */
    protected function curl($url){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);

        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = array(); //没有这个东东还真不行 不知道为什么
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;

    }

    /**
     * 接口加密
     * @param string $data
     * @return string
     */
    public function getEncrypt($data){
        $result = exec('/usr/etc/jdk1.8.0_151/bin/java AES '.$data,$encrypt,$return_var);
        return $result;
    }



}